package com.google.blockly.ohos.ui.fieldview;

import ohos.agp.components.BaseItemProvider;
import ohos.agp.components.Component;
import ohos.agp.components.ComponentContainer;
import ohos.agp.components.LayoutScatter;
import ohos.app.Context;
import com.google.blockly.ohos.ui.spinner.NiceSpinner;

import java.util.List;

/**
 * Common Code for Field DropDown Adapters
 * This makes a Spinner's width, the width of the currently selected item, not a one size fits all.
 */
public class FieldAdapter<T> extends BaseItemProvider {
    private Context context;
    private int resource;
    private List<T> mObjects;
    private NiceSpinner mNiceSpinner;


    public FieldAdapter(Context context, int resource, NiceSpinner mNiceSpinner) {
        this.mNiceSpinner = mNiceSpinner;
    }

    public FieldAdapter(Context context, int resource, List<T> objects, NiceSpinner mNiceSpinner) {
        this.context = context;
        this.resource = resource;
        this.mObjects = objects;
        this.mNiceSpinner = mNiceSpinner;
    }

    @Override
    public int getCount() {
        return mObjects != null ? mObjects.size() : 0;
    }

    @Override
    public Object getItem(int position) {
        return mObjects != null ? mObjects.get(position) : null;
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public Component getComponent(int position, Component component, ComponentContainer componentContainer) {
        if (component == null) {
            component = LayoutScatter.getInstance(context).parse(resource, componentContainer, false);
        }
        return component;
    }

    public void addItem(T var) {
        if (mObjects != null) {
            mObjects.add(var);
        }
    }

    public void clearAllItem() {
        if (mObjects != null) {
            mObjects.clear();
        }
    }
}
